<?php
class VmController extends Core_Controller
{
	public function indexAction()
	{
		if(! isset($_SESSION['user_id'])) $this->redirect('');
	    if(count($this->_http->getArvs())>1) throw new Exception("404 not found",404);
	    $status = 2; // all
	    if(count($this->_http->getArvs())==1)
	    {
	    	$getState = $this->_http->getParam('status');
	    	if($getState == 'start')
	    		$status = 1;
	    	else 
	    		if($getState == 'stop')
	    			$status = 0;
	    		  else
	    		  		throw new Exception("404 not found",404);	
	    }

	    $this->_view->title = "Quản lý máy ảo";
        $this->_view->activeClass = "vm";
        
        $user_id = $_SESSION['user_id'];
        
        $modelVm = new Model_Vm();
        
        $listStart = $modelVm->getVms($user_id,1);
        $now   = strtotime($modelVm->getNow());
        if($listStart != null )
        {
        	$countStart = count($listStart);
        	for($k = 0; $k< $countStart;$k++)
        	{
        	  $start = strtotime($listStart[$k]['start_date']);
        	  $used  = ceil(($now-$start)/60) + $listStart[$k]['usedtime'];
        	  if($used >= $listStart[$k]['duration'])
        	  {
        	  	$used = $listStart[$k]['duration'];
        	  	$modelVm->updateStopVm($listStart[$k]['vm_id'], $used);
        	  }
        	}
        }
        

        $this->_view->status  = $status;
        $this->_view->input_status = $status;
        
        $pagevm = '/'.$this->_http->getRequestUri();
        $_SESSION['pageVm'] = $pagevm;
        
	}
	
   
    public function pagingAction()
    {
    	if(! isset($_SESSION['user_id'])) $this->redirect('');
    	$user_id = $_SESSION['user_id'];
    	
    	$this->_view->layout(false);
    	
    	if(count($this->_http->getArvs()) != 2) 
    		$this->_view->status = 0;
    	else 
    	{
    		$p = $this->_http->getParam('p');
    		$s = $this->_http->getParam('s');
    		
	        if(($p == null)||($s == null)) 
	        	$this->_view->status = 0;
	        else 
	        {
	        	$p = intval($p);
	        	$s = intval($s);
	        	$u = intval($user_id);

	        	$modelVm = new Model_Vm();
       		    $now   = strtotime($modelVm->getNow());
	       		
       		    $listVm  = $modelVm->getVms($u,$s);
       		    
		        if($listVm != null)
		        {
		        	$paginator = new Utilities_Paginator($listVm);
		        	$paginator->setItemCountPerPage(5);
		        	$paginator->setCurrentPageNumber($p);
		        	$this->_view->list = $paginator->getResult();
		        	$this->_view->now  = $now;
		        	$this->_view->paginator = $paginator;
		        	$this->_view->indexStart = ($paginator->getCurrentPageNumber()-1) * $paginator->getItemCountPerPage() + 1;
		        	$this->_view->status = 1;
		        	if(isset($_SESSION['pageVm']))
       					$_SESSION['pageVm'] = $_SESSION['pageVm'].'#p'.$p;
		        }
		        else 
		        	$this->_view->status = 0;
	        }
    	}
    	
    }
    	
	
	public function createAction()
	{
		if(count($this->_http->getArvs())>0) throw new Exception("404 not found",404);
        if(! isset($_SESSION['user_id'])) $this->redirect('');
        $this->_view->title = "Thêm máy ảo";
        $this->_view->activeClass = "vm";
        
        $modelPackage = new Model_Package();
        $this->_view->listPackage = $modelPackage->getPackages_Templates();
        
        //status  0: chua submit , 1: da submit va co loi , 2: submit thanh cong
        $status = 0;
        $message = '';
        $vmname  = '';
        $duration = '';
        $package  = '';
        
        if(isset($_POST['vmname']))
        {
        	$security = new Core_Security();
        	$vmname   = $security->xss_clean(trim($_POST['vmname']));
            $duration = $security->xss_clean(trim($_POST['time']));
            $package  = trim($_POST['package']);
            
            $duration = intval($duration);
            $status   = 1;
            
            
            $modelVm = new Model_Vm();
            
            if($vmname == "")
            {
              $message = "Chưa nhập tên máy ảo";	
            }
            else
               if($duration <= 0)
               {
               	  $message = "Thời gian phải là số nguyên dương";
               }
               else
               {
               	 if($modelVm->checkVmname($vmname))
               	 	$message = "Tên máy ảo đã tồn tại";
               	 else
               	 {
               	 	$package_info = $modelPackage->getPackage_Template($package);
               	    if(($package_info == null) or (! file_exists($package_info[0]['template_path'])))
               	    {
               	    	$message = "Không sử dụng được gói dịch vụ này";
               	    }
               	    else
               	    {
               	    	$template_path = $package_info[0]['template_path'];
               	    	$user_id = $_SESSION['user_id'];
               	    	$modelUser = new Model_User();
               	    	$sum_credit = $modelUser->getCredit($user_id);
               	    	$pph = intval($package_info[0]['pph']);
               	    	if($duration * $pph > $sum_credit)
               	    	{
               	    		$message = "Không đủ tiền trong tài khoản để thực hiện giao dịch này";
               	    	}
               	    	else
               	    	{
               	    		$user_info = $modelUser->getUser($user_id);
               	    		$username  = $user_info[0]['username'];
               	    		$credit    = $sum_credit - $duration * $pph;
               	    		$apiVm     = new Api_Vm();
               	    		$ok  = $apiVm->createVm($username, $vmname, $template_path);
               	    		if($ok)
               	    		{
               	    			$modelVm->insertVm($user_id, $package, $vmname, $duration);
               	    			$modelUser->updateCredit($credit, $user_id);
               	    			$status = 2;
               	    			$this->redirect('/vm');
               	    		}
               	    		else 
               	    		{
               	    			$message = "Không thêm được do lỗi hệ thống";
               	    		}
               	    	}
               	    }
               	 }
               }
           
        }
        
        $this->_view->status = $status;
        $this->_view->message = $message;
        $this->_view->input_vmname = $vmname;
        $this->_view->input_time = $duration;
        $this->_view->input_package = $package;
	}
	
	public function startAction()
	{
		if(! isset($_SESSION['user_id'])) $this->redirect('');
		$user_id = $_SESSION['user_id'];
		$modelUser = new Model_User();
		$user_info = $modelUser->getUser($user_id);
        $username  = $user_info[0]['username'];
        
		if(count($this->_http->getArvs()) != 1 ) throw new Exception("404 not found",404);
        $id = $this->_http->getParam('id');
        if($id == null) throw new Exception("404 not found",404);
        
        $this->_view->layout(false);
        
        $modelVm = new Model_Vm();
        $vm_info = $modelVm->getVm($id);
          
        if(($vm_info != null) && ($vm_info[0]['status'] == 0) && ($vm_info[0]['user_id'] = $user_id))
        {
           	  $time = $vm_info[0]['duration'] + $vm_info[0]['extratime'] - $vm_info[0]['usedtime'];
           	  if($time > 0)
           	  {
           	  	$duration = $time/60;
           	  	$apiVm     = new Api_Vm();
           	  	
           	  	$info      = $apiVm->startVm($username,$vm_info[0]['vmname'],$vm_info[0]['cpu'],$vm_info[0]['ram'],$duration);
           	  	if($info['default_name'] != '')
           	  	{
           	  		$modelVm->updateStartVm($id, $vm_info[0]['duration'], $vm_info[0]['extratime'],$info['ip'], $info['host'], $info['default_name']);
           	  	}
           	  } 
        }
       if(isset($_SESSION['pageVm']))
       		$this->redirect($_SESSION['pageVm']);
       	else 
       		$this->redirect('/vm');
	}
	
	public function stopAction()
	{
		if(! isset($_SESSION['user_id'])) $this->redirect('');
		$user_id = $_SESSION['user_id'];
		
		if(count($this->_http->getArvs()) != 1 ) throw new Exception("404 not found",404);
        $id = $this->_http->getParam('id');
        if($id == null) throw new Exception("404 not found",404);
        
        $this->_view->layout(false);
        
        $modelVm = new Model_Vm();
        $vm_info = $modelVm->getVm($id);
        
        if(($vm_info != null) && ($vm_info[0]['status'] == 1) && ($vm_info[0]['user_id'] == $user_id))
        {
        	  $now   = strtotime($modelVm->getNow());
        	  $start = strtotime($vm_info[0]['start_date']);
        	  $used  = ceil(($now-$start)/60) + $vm_info[0]['usedtime'];
        	  if($used >= $vm_info[0]['duration'])
        	  {
        	  	$used = $vm_info[0]['duration'];
        	  	$ok   = true;
        	  }
        	  else 
        	  {
        	  	$apiVm     = new Api_Vm();
           	  	$ok      = $apiVm->stopVm($vm_info[0]['default_name']);
        	  }
           	  if($ok)
           	  {
           	  	$modelVm->updateStopVm($id, $used);
           	  }
           	 
        }
        
       if(isset($_SESSION['pageVm']))
       		$this->redirect($_SESSION['pageVm']);
       	else 
       		$this->redirect('/vm');
	}
	
	public function upgradeAction()
	{
		if(! isset($_SESSION['user_id'])) $this->redirect('');
		$user_id = $_SESSION['user_id'];
		
		if(count($this->_http->getArvs()) != 1 ) throw new Exception("404 not found",404);
        $id = $this->_http->getParam('id');
        if($id == null) throw new Exception("404 not found",404);
        
        $this->_view->title = "Gia hạn thời gian";
        $this->_view->activeClass = "vm";
        
        $modelVm = new Model_Vm();
        $vm_info = $modelVm->getVm($id);
        
        if(($vm_info == null) || ($vm_info[0]['user_id'] != $user_id))
        {
        	if(isset($_SESSION['pageVm']))
       			$this->redirect($_SESSION['pageVm']);
       		else 
       			$this->redirect('/vm');
        }
        
        //status  0: chua submit , 1: da submit va co loi , 2: submit thanh cong
        $status   = 0;
        $message  = '';
        $vmname   = $vm_info[0]['vmname'];
        $duration = $vm_info[0]['duration'] + $vm_info[0]['extratime'];
        $package_id = $vm_info[0]['package_id'];
        $extratime = '';
        
        if(isset($_POST['extratime']))
        {
           $status = 1;
           $extra = intval($_POST['extratime']);
           if($extra <= 0)
           {
           	 $message = "Thời gian phải là số nguyên dương";
           }
           else 
           {
           	 			$modelUser = new Model_User();
               	    	$sum_credit = $modelUser->getCredit($user_id);
               	    	$pph = intval($vm_info[0]['pph']);
               	    	if($extra * $pph > $sum_credit)
               	    	{
               	    		$message = "Không đủ tiền trong tài khoản để thực hiện giao dịch này";
               	    	}
               	    	else
               	    	{
               	    		$modelUser->updateCredit($sum_credit - $extra * $pph, $user_id);
               	    		$modelVm->updateExtratime($id, $extra);
               	    		$status = 2;
               	    		if(isset($_SESSION['pageVm']))
       							$this->redirect($_SESSION['pageVm']);
       						else 
       							$this->redirect('/vm');
               	 		}
           }          	
        }
             
        
        $this->_view->status = $status;
        $this->_view->message = $message;
        $this->_view->vm_id   = $id;
        $this->_view->input_vmname = $vmname;
        $this->_view->input_time = $duration;
        $this->_view->package_id = $package_id;
        $this->_view->input_extratime = $extratime;  
	}
}